package com.tedu.springmvc01request.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
	
	//完成注册功能，浏览器发get请求
	@GetMapping("/reg1")
	public String register1(String username,
			String password) {
		return"注册成功";
	}
	
	//完成注册功能，浏览器发post请求
		@PostMapping("/reg2")
		public String register2(String username,
				String password) {
			return"注册成功";
		}
		
		//完成注册功能，能接收get和post两种请求
		//index.html两个form action=reg3
		//重启服务器
				@RequestMapping("/reg3")
				public String register3(String username, String password) {
					return"注册成功";
				}
		@RequestMapping("/reg4")
		//console关闭程序
		//main() run as  tomcat started on ports
		//地址栏直接输入
		//http://localhost:8080/reg4?username=a&password=1
		//开一个窗口
		//http://localhost:8080/reg4?username=b&password=2
		//默认情况下，每次请求调用的controller是同一个对象
		//1,每次都要演示
		//2,少演示
		public String register4(User user) {
			return "注册成功 username="
		+user.getUsername()+"<br>"+this.toString();
		}
		
		@RequestMapping("/reg5")
		//http://localhost:8080/reg5?username=a&password=1
		public String register5
		(HttpServletRequest request) {
			String username=request
					.getParameter("username");
			String password=request
					.getParameter("password");
			String userIp=request.getRemoteAddr();
			String s=username+","+password+","+userIp;
			return s;
		}
		//用response返回数据给浏览器
		@RequestMapping("/reg6")
		//http://localhost:8080/reg6
		public void register6(HttpServletResponse response)
				throws Throwable 
		{
			//告诉浏览器返回的是html还是json
			response.setContentType("text/html");
			//告诉浏览器返回内容的编码
			response.setCharacterEncoding("UTF-8");
			//printWriter写数据
			PrintWriter printWriter=response.getWriter();
			printWriter.println("注册成功");
			
		}
		
		//登录后，服务器往浏览器中写cookie
		@RequestMapping("/login")
		//f12 network response header -->set-cookie
		//http://localhost:8080/login?username=zhangjiujun
		
		public String login(String username,
				HttpServletResponse response) {
			//创建cookie
			Cookie cookie=new Cookie("username", username);
			//把cookie发给浏览器
			response.addCookie(cookie);
			return "往浏览器写入cookie";
			
		}
		
		
		
		
		
		

}
